package reflection.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @program: javase
 * @description: JDK动态代理, 目标类必须实现接口
 * @author: lld
 * @create: 2020-11-23 19:09
 **/
public class ProxyTest {
    public static void main(String[] args) {
        Factory proxyInstance = (Factory) ProxyFactory.getProxyInstance(new ClothFactory());
        proxyInstance.produceCloth();
    }
}
////目标类
//class ClothFactory implements Factory {
//
//    @Override
//    public void produceCloth() {
//        System.out.println("produce Cloth");
//    }
//}
class ProxyFactory {
    //调用此方法返回代理类对象
    public static Object getProxyInstance(Object obj) {//目标对象
//        匿名内部类方式
        Object proxyInstance = Proxy.newProxyInstance(obj.getClass().getClassLoader(),
                obj.getClass().getInterfaces(),
                (proxy, method, args) -> {
//                    System.out.println(proxy);
//                    System.out.println(method.getName());
//                    System.out.println(args);
                    return method.invoke(obj, args);
                });
        return proxyInstance;

    }
}
//class ProxyFactory {
//    //调用此方法返回代理类对象
//    public static Object getProxyInstance(Object obj) {//被代理类对象
//        MyInvocationHandler invocationHandler = new MyInvocationHandler();
//        invocationHandler.bind(obj);//绑定被代理类对象
//        Object proxyInstance = Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), invocationHandler);
//        return proxyInstance;
//    }
//}
//
////自定义InvocationHandler实现类
//class MyInvocationHandler implements InvocationHandler {
//    private Object obj;
//
//    public void bind(Object obj) {
//        this.obj = obj;
//    }
//
//    @Override
//    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//        Object invoke = method.invoke(obj, args);
//        return invoke;
//    }
//}